package pl.sind.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public abstract class BaseHttpResponse<T> extends BaseHttpRequestResponse<T>
		implements HttpResponse<T> {
	private static final int BUFFER_SIZE = 50;

	private String body;

	public String getBody() throws HttpRequestException {
		if (body == null) {
			body = readInputStream(getInputStream(), getContentSize());
		}
		return body;
	}

	private String readInputStream(InputStream in, int length)
			throws HttpRequestException {
		try{
		ByteArrayOutputStream data = null;
		if (length > 0) {
			data = new ByteArrayOutputStream(length);
		} else {
			data = new ByteArrayOutputStream(2 * BUFFER_SIZE);
		}

		byte[] buffer = new byte[BUFFER_SIZE];
		int cnt = in.read(buffer);
		while (cnt > 0) {
			data.write(buffer, 0, cnt);
			cnt = in.read(buffer);
		}
		in.close();
		data.close();

		return new String(data.toByteArray(), HttpStrings.DEFAULT_ENCODING);
		}catch (IOException e){
			throw new HttpRequestException(e);
		}
	}

}
